package qj.app.trader;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import qj.tool.http.WebSession;
import qj.tool.string.StringExtractor;
import qj.util.RegexUtil;
import qj.util.col.Tree;
import qj.util.funct.P1;

public class BonBanhProvider {
	public static void main(String[] args) {

		WebSession webSession = new WebSession();
		String content = webSession.getString("http://www.bonbanh.com");
		
		Tree<String> root = new Tree<String>(null);
		
		String catStr = StringExtractor.nextBetween("<div id=\"m-cate\" class=\"yellow-box\">", "\">Tất cả hãng</a>", content);
		
		StringExtractor catExtractor = new StringExtractor(catStr);
		
		
		while (true) {
			boolean theEnd = false;
			
			String brand = catExtractor.getNext("class=\"mtop-item\" href=\"oto/(\\w+)\\.html\"", 1);
			if (brand==null) {
				break;
			}
			
			final Tree<String> brandTree = new Tree<String>(brand);
			root.add(brandTree);
			
			String productNameStr = catExtractor.untilNext("<li id=\"mp");
			if (productNameStr==null) {
				productNameStr = catExtractor.toEnd();
				theEnd = true;
			}
			
			RegexUtil.each(Pattern.compile(">([^<]+)</a></li>"), productNameStr, new P1<Matcher>() {public void e(Matcher matcher) {
				String productName = matcher.group(1);
				if (!"khác".equalsIgnoreCase(productName)) {
					brandTree.add(new Tree<String>(productName));
				}
			}});
			if (theEnd) {
				break;
			}
		}
		System.out.println(root);
	}
}
